package initialize

import (
	"a_plus_station/global"
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/mojocn/base64Captcha"
	"image/color"
	"time"
)

var ctx = context.Background()

// RedisStore 实现 base64Captcha.Store 接口
type RedisStore struct {
	client *redis.Client
}

// Set 存储验证码
func (s *RedisStore) Set(id string, value string) error {
	err := s.client.Set(ctx, id, value, 10*time.Minute).Err() // 验证码有效期为10分钟
	return err
}

// Get 获取验证码
func (s *RedisStore) Get(id string, clear bool) string {
	val, err := s.client.Get(ctx, id).Result()
	if err != nil {
		return ""
	}
	if clear {
		s.client.Del(ctx, id) // 验证后清除验证码
	}
	return val
}

// Verify 验证验证码
func (s *RedisStore) Verify(id, answer string, clear bool) bool {
	v := s.Get(id, clear)
	return v == answer
}

func Initcaptcha() {
	dsn := fmt.Sprintf("%s:%d",
		global.ServerConfig.RedisConfigInfo.Host,
		global.ServerConfig.RedisConfigInfo.Port,
	)
	// 初始化 Redis 客户端
	redisClient := redis.NewClient(&redis.Options{
		Addr: dsn,
	})

	// 创建 RedisStore 实例
	store := &RedisStore{client: redisClient}

	rgb := &color.RGBA{
		R: 52,
		G: 52,
		B: 52,
		A: 25,
	}

	source := "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
	// 生成验证码
	digit := base64Captcha.NewDriverString(
		80,
		240,
		0,
		0,
		4,
		source,
		rgb,
		nil,
		[]string{"actionj.ttf"},
	)
	cp := base64Captcha.NewCaptcha(digit, store)
	global.CP = cp
}
